package com.chen.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.common.R;
import com.chen.dto.DishDto;
import com.chen.entity.Category;
import com.chen.entity.Dish;
import com.chen.entity.DishFlavor;
import com.chen.service.CategoryService;
import com.chen.service.DishFlavorService;
import com.chen.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "dishCache" , allEntries = true)
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        return R.success("新增菜品成功");
    }
    /**
     * 菜品信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {

            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 删除菜品
     */
    @DeleteMapping
    @CacheEvict(value = "dishCache" , allEntries = true)
    public R<String> delete(Long[] ids){
        //获取所有菜品对象
        List<Dish> dishes = dishService.listByIds(Arrays.asList(ids));
        for (Dish dish : dishes) {
            //删除菜品前查看是否绑定口味，如果绑定口味将口味一起删除
            LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
            lqw.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> list = dishFlavorService.list(lqw);
            //如果集合不为空 则表示 有绑定的口味 , 将口味删除
            if (list.size() > 0 ){
                for (DishFlavor dishFlavor : list) {
                    Long id = dishFlavor.getId();
                    dishFlavorService.removeById(id);
                }

            }
            //再删除菜品
            dishService.removeById(dish.getId());
        }

        return R.success("删除成功");
    }

    /**
     * 通过id查询
     */
    @GetMapping("/{id}")
    public R<DishDto> selectById(@PathVariable Long id){
        //通过id查询菜品信息
        Dish dish = dishService.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        //查询菜品口味 添加到dto对象中
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,id);
        List<DishFlavor> dishFlavors = dishFlavorService.list(lqw);

        dishDto.setFlavors(dishFlavors);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     */

    @PutMapping
    @CacheEvict(value = "dishCache" , allEntries = true)
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        return R.success("修改成功");
    }

    /**
     * 菜品停售起售
     */
    @PostMapping("/status/{stu}")
    @CacheEvict(value = "dishCache" , allEntries = true)
    public R<String> stopSelling(@PathVariable int stu, Long[] ids){
        log.info("ids: {}",ids.toString());
        //查询到所有菜品对象
        List<Dish> dishes = dishService.listByIds(Arrays.asList(ids));
        if(stu == 0){
            for (Dish dish : dishes) {
                //将状态修改为停售 ：0
                dish.setStatus(0);
                //将数据库中的数据修改
                dishService.updateById(dish);
            }
        }
        if (stu == 1){
            for (Dish dish : dishes) {
                //将状态修改为启售 ：1
                dish.setStatus(1);
                //将数据库中的数据修改
                dishService.updateById(dish);
            }
        }


        return R.success("修改成功");
    }
    /**
     * 根据条件查询对应的菜品数据
     * @param dish
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "dishCache", key = "#dish.categoryId+'_'+#dish.status")
    public R<List<DishDto>> list(Dish dish){
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }

}   